/* 
* Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd. 
* SPDX-License-Identifier: MulanPSL-2.0 
*/ 

import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { FormattedMessage, useIntl, history, request } from '@umijs/max';
import { Modal, Button, Space, Spin } from 'antd'
import CodeEditer from '@/components/public/CodeEditer';

/**
 * LogModal 对话框
 */
export default forwardRef((props: any, ref: any) => {
  const [loading, setLoading] = useState(false)
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState('');
  const [title, setTitle] = useState('');

  // 1.请求数据
  const getRequestData = async (url: string) => {
    setLoading(true);
      try {
        const res = await request(url, { skipErrorHandler: true, })
        if (typeof res === 'string') {
          setData(res)
        } else if (res instanceof Object) {
          // json对象 转 格式化字符串。
          const dataSet = JSON.stringify(res, null, 4)
          setData(dataSet)
        }
        setLoading(false);
      } catch (err: any) {
        // message.error('查询数据失败！');
        setLoading(false);
      }
  }

  useImperativeHandle(
    ref,
    () => ({
        show: ({ title= '', url}: any) => {
          setVisible(true)
          setTitle(title);
          if (url) getRequestData(url)
        },
    })
  )

  const handleOk = () => {
    setVisible(false);
    setData('')
  };
  const handleCancel = () => {
    setVisible(false);
    setData('')
  };

	return (
      <Modal
        title={<Space>{title}</Space>}
        open={visible}
        maskClosable={true}
        width={960}
        confirmLoading={loading}
        onCancel={handleCancel}
        footer={
          <Button type="primary" onClick={handleOk} style={{marginRight:12}}>
            <FormattedMessage id="log.modal.btn.confirm" />
          </Button>
        }
        bodyStyle={{ padding: '20px 30px',background: '#f8f8f8'}}
      >
        <Spin spinning={loading}>
          <CodeEditer code={data} lineNumbers height={500} />
        </Spin>
      </Modal>
	);
});